import 'package:mason_logger/mason_logger.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/Ubuntu/ubuntu_get_mirro_list.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/Yoyo/yoyo_get_mirro_list.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/Yoyo/yoyo_is_exist.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/utils/generate_apt_fast_config_file.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/utils/network_test.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/utils/test_mirro_speed.dart';
import 'package:yoyo_get_fast_mirror/src/commands/modules/getfastmirror/utils/write_mirror_into_file.dart';
import 'package:yoyo_get_fast_mirror/i18n.dart';

final Map<String, dynamic> status = {};
final Logger _logger = Logger();

final outputYoyo = lightGreen.wrap('Yoyo Mirrors:');
final outputUbuntu = lightGreen.wrap('Ubuntu Mirrors:');

Future<Map<String, dynamic>> getFastMirror({bool onlyTest = false}) async {
  //首先测试网络链接
  if (!await networkTest()) {
    status['success'] = false;
    status['msg'] = Error.network;
    return status;
  }
  // 如果 yoyo-os.list 存在，获取Yoyo镜像地址
  final yoYoMirrorList = yoyoIsExist() ? await yoyoGetMirrorList() : ['none'];
  if (yoyoIsExist()) {
    _logger.info("\n$outputYoyo\n${yoYoMirrorList.join('\n')}\n");
  }
  // 如果 yoyo-os.list 存在，测试Yoyo镜像并获取时间和排序后的Map
  final sortedUrlListAndTimeYoyo = yoyoIsExist()
      ? await testMirroSpeed(yoYoMirrorList)
      : [
          {'url': '', 'time': 'none'}
        ];
  // 获取Ubuntua镜像地址
  final ubuntuMirrorList = ubuntuGetMirrorList();
  //测试Ubuntu镜像并获取时间和排序后的Map
  _logger.info("\n$outputUbuntu\n${ubuntuMirrorList.join('\n')}\n");
  final sortedUrlListAndTimeUbuntu = await testMirroSpeed(ubuntuMirrorList);
  //生成config
  if (!onlyTest) {
    try {
      generateAptFastConfigFile(
        sortedUrlListAndTimeYoyo,
        sortedUrlListAndTimeUbuntu,
      );
    } catch (e) {
      status['success'] = false;
      status['msg'] = Error.generateConfig;
      return status;
    } finally {
      status['success'] = true;
    }
    //写入镜像源文件
    //如果 yoyo-os.list 存在，Yoyo
    if (yoyoIsExist()) {
      final fastestYoyoMirror =
          sortedUrlListAndTimeYoyo.first.entries.first.value;
      writeMirrorIntoFile(
        fastestYoyoMirror,
        '/etc/apt/sources.list.d/yoyo-os.list',
      );
    }
    //Ubuntu
    final fastestUbuntuMirror =
        sortedUrlListAndTimeUbuntu.first.entries.first.value;
    writeMirrorIntoFile(
      fastestUbuntuMirror,
      '/etc/apt/sources.list',
    );
  }
  //返回执行结果
  return status;
}
